package com.xianwan.module;

import java.util.Date;

import com.xianwan.bean.UrlResult;
import com.xianwan.entity.Logs;
import com.xianwan.entity.Url;
import com.xianwan.util.Util;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;

/**
 * @author Howe
 */
@IocBean
@Fail("http:500")
public class UrlModule extends BaseModule {

    @Inject("java:$conf.get('urls.url')")
    protected String URLS_URL;
    @Inject("java:$conf.get('urls.key')")
    protected String URLS_KEY;
    @Inject("java:$conf.get('urls.defUrl')")
    protected String URLS_DEFURL;

    /**
     * 短网址访问
     *
     * @param key
     * @return
     */
    @GET
    @At("/*")
    @Ok("redirect:${obj}")
    public String redirect(String key) {

        if (Strings.isNotBlank(key)) {

            Url urls = dao.fetch(Url.class, Cnd.where("shortKey", "=", key));
            if (!Lang.isEmpty(urls)) {

                Logs log = new Logs();
                log.setReferer(Strings.isBlank(Mvcs.getReq().getHeader(
                        "Referer")) ? "Direct" : Mvcs.getReq().getHeader(
                        "Referer"));
                log.setShortKey(key);
                log.setAccessAgent(Util.getAgent(Mvcs.getReq()));
                log.setAccessTime(new Date());
                log.setAccessIp(Lang.getIP(Mvcs.getReq()));
                dao.insert(log);
                return urls.getLongUrl();
            } else {
                return URLS_DEFURL;
            }
        } else {
            return URLS_DEFURL;
        }
    }

    /**
     * 网址缩短
     *
     * @param token
     * @param url
     * @param key
     * @return
     */
    @Ok("json")
    @At("/api/short")
    public UrlResult shortlUrl(@Param("token") String token,
                               @Param("url") String url,
                               @Param("key") String key) {
        try {
            url = Util.Url.decode(url);
            if (Strings.isNotBlank(token)
                    && token.equals(Lang.md5(url + URLS_KEY))
                    && Strings.isNotBlank(url) && Strings.isUrl(url)) {

                if (Strings.isNotBlank(key)) {

                    Url urls = dao.fetch(Url.class, Cnd.where("shortKey", "=", key));
                    if (urls != null) {
                        urls.setAddTime(new Date());
                        urls.setTitle(Util.getUrlTitle(url));
                        urls.setLongUrl(url);
                        dao.update(urls);
                    } else {
                        urls = new Url();
                        urls.setAddTime(Times.now());
                        urls.setTitle(Util.getUrlTitle(url));
                        urls.setLongUrl(url);
                        urls.setShortKey(key);
                        dao.fastInsert(urls);
                    }
                    return UrlResult.Short(URLS_URL + key);
                } else {

                    Url urls = dao.fetch(Url.class, Cnd.where("longUrl", "=", url));
                    key = Lang.isEmpty(urls) ? null : urls.getShortKey();
                    if (Strings.isNotBlank(key)) {
                        return UrlResult.Short(URLS_URL + key);
                    } else {
                        key = Util.ShortText(url)[0];
                        urls = new Url();
                        urls.setAddTime(new Date());
                        urls.setTitle(Util.getUrlTitle(url));
                        urls.setLongUrl(url);
                        urls.setShortKey(key);
                        dao.fastInsert(urls);
                        return UrlResult.Short(URLS_URL + key);
                    }
                }
            }
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
        return UrlResult.Short(null);
    }

    /**
     * 短网址还原
     *
     * @param token
     * @param url
     * @return
     */
    @Ok("json")
    @At("/api/long")
    public UrlResult longUrl(@Param("token") String token, @Param("url") String url) {

        url = Util.Url.decode(url);
        if (Strings.isNotBlank(token)
                && Strings.equals(token, url + URLS_KEY)
                && Strings.isNotBlank(url) && Strings.isUrl(url)
                && url.indexOf(URLS_URL) >= 0) {

            Url urls = dao.fetch(Url.class,
                    Cnd.where("shortKey", "=", url.replaceAll(URLS_URL, "")));
            if (Lang.isEmpty(urls)) {
                return UrlResult.Long(urls.getLongUrl());
            }
        }
        return UrlResult.Long(null);
    }
}